package cn.jinjimi.app.main.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Roy
 * Date: 15/11/13
 */
public class MyViewPager extends android.support.v4.view.ViewPager {

    private boolean canTouch = true;

    private OnTranslationChangeListener mOnTranslationChangeListener;

    private int hightLimit;

    public MyViewPager(Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (canTouch) {
            try {
                return super.onTouchEvent(ev);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            }
            return false;
        } else {
            return false;
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (canTouch) {
            try {
                return super.onInterceptTouchEvent(ev);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            }
            return false;
        } else {
            return false;
        }
    }

    /* 禁止手势滑动 */
    public void setTouchEnable(boolean canTouch) {
        this.canTouch = canTouch;
    }

    @Override
    public void setTranslationY(float translationY) {
        super.setTranslationY(translationY);
        if (mOnTranslationChangeListener != null) {
            mOnTranslationChangeListener.onChange(getTranslationX(), translationY);
        }
    }

    public void setOnTranslationChangeListener(OnTranslationChangeListener listener) {
        this.mOnTranslationChangeListener = listener;
    }

    public interface OnTranslationChangeListener {
        void onChange(float translationX, float translationY);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (hightLimit > 0) {
            int size = MeasureSpec.getSize(heightMeasureSpec);
            size = size - hightLimit;
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setHightLimit(int hightLimit) {
        this.hightLimit = hightLimit;
        requestLayout();
    }
}
